#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import time
import random

# 设置标准输出编码为UTF-8（Windows兼容性）
if sys.platform == "win32":
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

def guessing_game():
    """数字猜谜游戏"""
    print("🎮 欢迎来到数字猜谜游戏！")
    print("=" * 40)
    
    while True:
        print("\n请选择游戏难度:")
        print("1. 简单 (1-10)")
        print("2. 中等 (1-50)")
        print("3. 困难 (1-100)")
        print("4. 地狱 (1-1000)")
        print("5. 退出游戏")
        
        print("请输入选择 (1-5):")
        
        try:
            choice = int(input())
            
            if choice == 1:
                play_game(1, 10, "简单")
            elif choice == 2:
                play_game(1, 50, "中等")
            elif choice == 3:
                play_game(1, 100, "困难")
            elif choice == 4:
                play_game(1, 1000, "地狱")
            elif choice == 5:
                print("感谢游玩！再见！👋")
                break
            else:
                print("❌ 无效选择，请输入 1-5 之间的数字！")
                
        except ValueError:
            print("❌ 请输入有效的数字！")
        except KeyboardInterrupt:
            print("\n\n游戏被用户中断")
            break

def play_game(min_num, max_num, difficulty):
    """开始游戏"""
    target = random.randint(min_num, max_num)
    attempts = 0
    max_attempts = calculate_max_attempts(max_num - min_num + 1)
    
    print(f"\n🎯 {difficulty}模式已开始！")
    print(f"我已经想好了一个 {min_num} 到 {max_num} 之间的数字")
    print(f"你有 {max_attempts} 次机会来猜中它！")
    print("-" * 40)
    
    start_time = time.time()
    
    while attempts < max_attempts:
        attempts += 1
        remaining = max_attempts - attempts + 1
        
        print(f"第 {attempts} 次猜测 (还剩 {remaining} 次):")
        
        try:
            guess = int(input())
            
            if guess < min_num or guess > max_num:
                print(f"❌ 请输入 {min_num} 到 {max_num} 之间的数字！")
                attempts -= 1  # 不计入尝试次数
                continue
            
            if guess == target:
                end_time = time.time()
                time_taken = end_time - start_time
                print(f"\n🎉 恭喜你！猜对了！")
                print(f"✅ 答案是: {target}")
                print(f"📊 用了 {attempts} 次尝试")
                print(f"⏱️ 用时 {time_taken:.1f} 秒")
                
                # 根据表现给出评价
                if attempts == 1:
                    print("🏆 太神了！一次就猜中！")
                elif attempts <= max_attempts // 3:
                    print("🌟 非常优秀！")
                elif attempts <= max_attempts // 2:
                    print("👍 表现不错！")
                else:
                    print("😅 还有进步空间！")
                
                ask_play_again()
                return
                
            elif guess < target:
                if remaining > 0:
                    print("📈 太小了！再试试更大的数字")
                    give_hint(guess, target, min_num, max_num)
            else:
                if remaining > 0:
                    print("📉 太大了！再试试更小的数字")
                    give_hint(guess, target, min_num, max_num)
                    
        except ValueError:
            print("❌ 请输入有效的数字！")
            attempts -= 1  # 不计入尝试次数
    
    print(f"\n💀 游戏结束！你用完了所有 {max_attempts} 次机会")
    print(f"😢 正确答案是: {target}")
    ask_play_again()

def calculate_max_attempts(range_size):
    """根据数字范围计算最大尝试次数"""
    import math
    return max(5, int(math.log2(range_size)) + 3)

def give_hint(guess, target, min_num, max_num):
    """给出提示"""
    diff = abs(guess - target)
    range_size = max_num - min_num + 1
    
    if diff <= range_size * 0.05:
        print("🔥 非常接近了！")
    elif diff <= range_size * 0.1:
        print("🌡️ 很接近！")
    elif diff <= range_size * 0.2:
        print("📍 比较接近")
    else:
        print("🌙 还挺远的")

def ask_play_again():
    """询问是否再玩一局"""
    while True:
        print("\n要再玩一局吗？(y/n):")
        response = input().lower().strip()
        
        if response in ['y', 'yes', '是', '要']:
            return
        elif response in ['n', 'no', '否', '不要']:
            print("感谢游玩！再见！👋")
            sys.exit(0)
        else:
            print("❌ 请输入 y 或 n")

if __name__ == "__main__":
    try:
        guessing_game()
    except Exception as e:
        print(f"\n❌ 游戏出现错误: {e}")
        sys.exit(1)
